﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;

namespace Sinacor.Infra.Common
{
    public class CrossAppDomainSingleton<T> : MarshalByRefObject where T : new()
    {
        private static Mutex _mtx = new Mutex();
        private static readonly string AppDomainName = "Singleton AppDomain";
        private static T _instance;

        private static AppDomain GetAppDomain(string friendlyName)
        {
            IntPtr enumHandle = IntPtr.Zero;
            Interop.mscoree.CorRuntimeHostClass host = new Interop.mscoree.CorRuntimeHostClass();
            try
            {
                host.EnumDomains(out enumHandle);

                object domain = null;
                while (true)
                {
                    host.NextDomain(enumHandle, out domain);
                    if (domain == null)
                    {
                        break;
                    }
                    AppDomain appDomain = (AppDomain)domain;
                    if (appDomain.FriendlyName.Equals(friendlyName))
                    {
                        return appDomain;
                    }
                }
            }
            finally
            {
                host.CloseEnum(enumHandle);
                Marshal.ReleaseComObject(host);
                host = null;
            }
            return null;
        }

        /// <summary>
        /// Recuperar a instancia da classe
        /// </summary>
        /// <returns></returns>
        public static T GetInstance()
        {
            try
            {
                _mtx.WaitOne();

                if (_instance == null)
                {
                    AppDomain appDomain = GetAppDomain(AppDomainName);

                    if (appDomain == null)
                    {
                        appDomain = AppDomain.CreateDomain(AppDomainName);
                    }

                    Type type = typeof(T);
                    T instance = (T)appDomain.GetData(type.FullName);

                    if (instance == null)
                    {
                        instance = (T)appDomain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);

                        appDomain.SetData(type.FullName, instance);
                    }

                    _instance = instance;
                }
            }
            finally
            {
                _mtx.ReleaseMutex();
            }

            return _instance;
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}
